package com.soup.lab.spring.web.controller;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.beans.PropertyEditorSupport;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/requestParam")
public class RequestParamTestController {

    @PostMapping("/post/form")
    public Map<String, Object> postForm(@RequestParam("id") Integer id,
                                        @RequestParam("name") String name,
                                        @RequestParam("queryParam") String queryParam) {
        return new HashMap<String, Object>(){{
            put("id", id);
            put("name", name);
            put("queryParam", queryParam);
        }};
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Monster.class, new PropertyEditorSupport(){
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(new Monster(null, text));
            }
        });
    }

    @PostMapping("/post/form2")
    public Map<String, Object> postForm2(@RequestParam Monster monster,
                                        @RequestParam("queryParam") String queryParam) {
        return new HashMap<String, Object>(){{
            put("monster", monster);
            put("queryParam", queryParam);
        }};
    }

    @Data
    @AllArgsConstructor
    public static class Monster {
        Integer id;
        String name;
    }

}
